package com.kamistoat.ruoyi.ruoyimodulessystem.controller;

import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kamistoat.ruoyi.ruoyiapisystem.domain.SysDictType;
import com.kamistoat.ruoyi.ruoyiapisystem.entity.SysDictTypeEntity;
import com.kamistoat.ruoyi.ruoyicommoncore.utils.StringUtils;
import com.kamistoat.ruoyi.ruoyicommoncore.utils.poi.ExcelUtil;
import com.kamistoat.ruoyi.ruoyicommoncore.web.controller.BaseController;
import com.kamistoat.ruoyi.ruoyicommoncore.web.domain.AjaxResult;
import com.kamistoat.ruoyi.ruoyicommoncore.web.page.TableDataInfo;
import com.kamistoat.ruoyi.ruoyicommonlog.annotation.Log;
import com.kamistoat.ruoyi.ruoyicommonlog.enums.BusinessType;
import com.kamistoat.ruoyi.ruoyicommonsecurity.annotation.RequiresPermissions;
import com.kamistoat.ruoyi.ruoyicommonsecurity.utils.SecurityUtils;
import com.kamistoat.ruoyi.ruoyimodulessystem.service.SysDictTypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

import static com.kamistoat.ruoyi.ruoyicommoncore.utils.page.PageUtils.startPage;


/**
 * 字典类型表
 *
 * @author kamistoat
 * @email linjianshanke@163.com
 * @date 2022-08-09 10:34:46
 */
@RestController
@RequestMapping("/dict/type")
public class SysDictTypeController extends BaseController {
    @Autowired
    private SysDictTypeService sysDictTypeService;

    /**
     * 匹配查询
     */
    @RequiresPermissions("system:dict:list")
    @GetMapping("/list")
    public TableDataInfo list(SysDictType sysDictType) {
        startPage();
        List<SysDictTypeEntity> sysDictTypeEntityList = sysDictTypeService.selectDictTypeList(
                StringUtils.isNull(sysDictType) ? new SysDictType() : sysDictType);
        return getDataTable(entity2Vo(sysDictTypeEntityList));
    }

    /**
     * 导出
     */
    @Log(title = "字典类型", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:dict:export")
    @PostMapping("/export")
    public void export(HttpServletResponse httpServletResponse, SysDictType sysDictType) {
        List<SysDictTypeEntity> sysDictTypeEntityList = sysDictTypeService.selectDictTypeList(sysDictType);
        ExcelUtil<SysDictType> util = new ExcelUtil<SysDictType>(SysDictType.class);
        util.exportExcel(httpServletResponse, entity2Vo(sysDictTypeEntityList), "字典类型");
    }

    /**
     * 查询字典类型详细
     */
    @RequiresPermissions("system:dict:query")
    @GetMapping(value = "/{dictId}")
    public AjaxResult getInfo(@PathVariable("dictId") Long dictId) {
        return AjaxResult.success(entity2Vo(
                sysDictTypeService.getOne(new QueryWrapper<SysDictTypeEntity>().eq("dict_id", dictId))
        ));
    }

    /**
     * 新增字典类型
     */
    @RequiresPermissions("system:dict:add")
    @Log(title = "字典类型", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDictType sysDictType) {
        if (sysDictTypeService.checkDictTypeUnique(sysDictType)) {
            return AjaxResult.error("新增字典类型'" + sysDictType.getDictType() + "'失败，字典类型已存在");
        }
        sysDictType.setCreateBy(SecurityUtils.getUserName());
        return toAjax(sysDictTypeService.save(vo2Entity(sysDictType)));
    }

    /**
     * 修改字典类型并更新缓存。
     * 注意，这里有个联动修改，需要同时修改该类型下的字典数据
     */
    @RequiresPermissions("system:dict:edit")
    @Log(title = "字典类型", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDictType sysDictType) {
        if (sysDictTypeService.checkDictTypeUnique(sysDictType)) {
            return AjaxResult.error("修改字典类型'" + sysDictType.getDictName() + "'失败，字典类型已存在");
        }
        sysDictType.setUpdateBy(SecurityUtils.getUserName());
        return toAjax(sysDictTypeService.updateDictTypeAndCache(vo2Entity(sysDictType)));
    }

    /**
     * 删除字典类型
     */
    @RequiresPermissions("system:dict:remove")
    @Log(title = "字典类型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dictIds}")
    public AjaxResult remove(@PathVariable("dictIds") Long[] dictIds) {
        sysDictTypeService.deleteDictTypeByIdsAndRemoveCache(dictIds);
        return success();
    }

    /**
     * 刷新字典缓存
     */
    @RequiresPermissions("system:dict:remove")
    @Log(title = "字典类型", businessType = BusinessType.CLEAN)
    @DeleteMapping("/refreshCache")
    public AjaxResult refreshCache() {
        sysDictTypeService.resetDictCache();
        return AjaxResult.success();
    }

    /**
     * 获取字典选择框列表
     */
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        List<SysDictTypeEntity> sysDictTypeEntityList = sysDictTypeService.selectDictTypeList(new SysDictType());
        return AjaxResult.success(entity2Vo(sysDictTypeEntityList));
    }


    /**
     * Entity 和 Vo类的转换
     */
    private List<SysDictType> entity2Vo(List<SysDictTypeEntity> sysDictTypeEntityList) {
        return
                sysDictTypeEntityList.stream().map(sysDictTypeEntity -> {
                    SysDictType sysDictType = new SysDictType();
                    BeanUtils.copyProperties(sysDictTypeEntity, sysDictType);
                    return sysDictType;
                }).collect(Collectors.toList());
    }

    private SysDictType entity2Vo(SysDictTypeEntity sysDictTypeEntity) {
        SysDictType sysDictType = new SysDictType();
        BeanUtils.copyProperties(sysDictTypeEntity, sysDictType);
        return sysDictType;
    }

    private List<SysDictTypeEntity> vo2Entity(List<SysDictType> sysConfigList) {
        return
                sysConfigList.stream().map(sysDictType -> {
                    SysDictTypeEntity sysDictTypeEntity = new SysDictTypeEntity();
                    BeanUtils.copyProperties(sysDictType, sysDictTypeEntity);
                    return sysDictTypeEntity;
                }).collect(Collectors.toList());
    }

    private SysDictTypeEntity vo2Entity(SysDictType sysDictType) {
        SysDictTypeEntity sysDictTypeEntity = new SysDictTypeEntity();
        BeanUtils.copyProperties(sysDictType, sysDictTypeEntity);
        return sysDictTypeEntity;
    }

}
